import 'package:basic_common/common_exports.dart';
import 'package:basic_common/logger_utils.dart';

import 'model/patient_data_list.dart';

class PatientController extends GetxController {
  TextEditingController searchController = TextEditingController();

  /// 拼音 相关 start
  final IndexNavigationListState state = IndexNavigationListState();
  ItemPositionsListener? itemPositionsListener;
  // listView 控制器
  List<String> headData = ["已关注患者", "已签约患者"];
  List<PinYinListyModel> patientList = [];
  // List<SortList> dataList = [
  //   SortList(label: '', children: [])
  // ];
  List<SortList> dataList = [];
  List indexList = [];
  final List<String> az = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "G",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ];

  /// 拼音 相关 end

// 下拉刷新
  RefreshController refreshController = RefreshController(initialRefresh: true);
  int pageSize = 5; //每页数量
  int pageNo = 1; //页数

  /// 下拉刷新
  onRefresh() async {
    pageNo = 1;
    await getPatientList();
  }

  /// 上拉加载
  onLoading() async {
    pageNo += 1;
    await getPatientList();
  }

  @override
  void onInit() {
    // TODO: implement onInit
    onRefresh();
    super.onInit();
  }

  /// 获取患者信息
  getPatientList() async {
    String url =
        '${HttpOptions.BASE_URL}${HttpUrl.PATIENT_LIST_URL}?pageSize=${pageSize}&pageNo=${pageNo}';
    HttpData res = await ApiService().getPatientList(data: {
      "scene": '1',
      "searchKeys": {'name': "", "phone": "", "tag": ""},
      "sceneDesc": "医生端患者列表",
      'pageOff': 1
    });
    if (res.code == 1) {
      if (res.data == null) {
        return;
      }
      PatientDataList patientDataList = PatientDataList.fromJson(res.data);
      if (patientDataList.total! > 0) {
        List<PatientData>? pList = patientDataList.list!;
                // mPatinentList.value = pList;
        // if (pageNo == 1) {
        //   mPatinentList.value = pList;
        // } else {
        //   mPatinentList.value = [...mPatinentList, ...pList];
        // }
        pList.forEach((data) {
          String now = '#';
          // 1.获取名字的第一个拼音
          String nowPin = PinyinHelper.getFirstWordPinyin(data.nickName ?? '');
          if (nowPin.length > 0) {
            now = indexList.contains(nowPin.substring(0, 1).toUpperCase())
                ? '#'
                : nowPin.substring(0, 1);
          }
          PinYinListyModel pModel =
              PinYinListyModel(info: data ?? '', pin: now.toUpperCase());
          patientList.add(pModel);
        });

        // 排序
        patientList.sort((PinYinListyModel a, PinYinListyModel b) {
          if (a.pin == '#') {
            return 1;
          }
          if (b.pin == '#') {
            return 0;
          }
          return a.pin.compareTo(b.pin);
        });

        // 去重排序
        List _arr = [];
        var s = Set();
        for (var i = 0; i < patientList.length; i++) {
          _arr.add(patientList[i].pin);
        }
        s.addAll(_arr);
        // 转为Model类型列表
        s.toList().forEach((element) {
          element = SortList(label: element, children: []);
          dataList.add(element);
        });

        // 生成UI列表显示数据
        for (var element in dataList) {
          for (var item in patientList) {
            if (element.label == item.pin) {
              element.children.add(item.info);
            }
          }
        }
        // if (pList.length < pageSize) {
        //   refreshController.loadNoData();
        // } else {
        //   refreshController.loadComplete();
        // }
        // refreshController.refreshCompleted();
      }
          LoggerUtil.i("患者列表====${dataList.toList().toString()}");

      update(['patientInfo']);
    }

    update(['patientInfo']);
  }

  // 改变索引下标
  void changeIndex(index) {
    state.currentIndex = index;
    update(['patientInfo']);
  }
}
